<template>
  <div class="box">
    <el-card style="margin: 20px">
      <!-- 新增按钮 -->
      <el-button
        type="primary"
        style="float: right; margin: 5px 5px 15px 5px"
        size="medium "
        @click="addColumn()"
        >新增子栏目</el-button
      >
    </el-card>
    <!-- 表格 -->
    <el-card style="margin: 20px">
      <el-table
        :data="list"
        stripe
        border
        size="medium "
        style="width: 100%"
        :header-cell-style="{ background: '#ebeef5' }"
      >
        <el-table-column type="index" label="序号" width="70">
        </el-table-column>
        <el-table-column prop="moduleName" label="父栏目名称">
        </el-table-column>
        <el-table-column prop="columnName" label="子栏目名称">
        </el-table-column>
        <el-table-column prop="columnStatus" label="栏目状态">
          <template slot-scope="{ row }">
            {{ row.columnStatus == 1 ? "标题" : "标题&导航" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" icon="el-icon-edit" @click="editColumn(row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-setting"
              @click="setImg(row)"
              >{{
                row.columnStatus == 1 ? "设为导航图" : "取消导航图"
              }}</el-button
            >
            <el-popconfirm
              title="确认删除这个栏目吗？"
              @confirm="deleteColumn(row)"
            >
              <el-button type="text" slot="reference" icon="el-icon-delete"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加与编辑弹窗 -->
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="40%"
        @open="open"
        :before-close="handleClose"
      >
        <el-form
          ref="ruleFrom"
          label-width="150px"
          :model="formList"
          :rules="rules"
        >
          <el-form-item label="选择父栏目" prop="moduleId">
            <el-select
              v-model="formList.moduleId"
              placeholder="请选择"
              style="width: 350px"
              size="medium "
            >
              <el-option
                v-for="column in columnList"
                :key="column.id"
                :label="column.columnName"
                :value="column.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="输入子栏目" prop="columnName">
            <el-input
              v-model="formList.columnName"
              style="width: 350px"
              size="medium "
              placeholder="请输入子栏目名"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-upload
              class="avatar-uploader"
              :headers="headers"
              action="/drug/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <div slot="tip" class="el-upload__tip">
                请上传一张图片（大小不能超1MB,图片格式jpg,jpeg,png）
              </div>
              <img v-if="formList.image" :src="formList.image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrEdit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 20px; text-align: center"
        :current-page="page"
        :page-size="limit"
        :page-sizes="[8, 10, 15]"
        layout="prev, pager, next,jumper,->,total,sizes "
        :total="total"
        @current-change="getList"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
// 获取token
import { getToken } from "@/utils/auth";
export default {
  name: "",
  data() {
    return {
      // 列表数据
      list: [],
      // 页数
      page: 1,
      // 展示数据条数
      limit: 8,
      // 数据条数
      total: 20,
      // 控制弹窗字段
      dialogVisible: false,
      // 弹窗名
      title: "",
      // 图片路径
      imageUrl: "",
      // 表单数据
      formList: {
        columnName: "",
        image: "",
        moduleId: "",
      },
      // 栏目列表数据
      columnList: [],
      // 表单验证
      rules: {
        moduleId: [
          { required: true, message: "请选择父栏目", trigger: "change" },
        ],
        columnName: [
          { required: true, message: "请输入子栏目名称", trigger: "blur" },
        ],
      },
    };
  },
  // 组件挂载完毕，获取数据
  mounted() {
    this.getList();
  },
  methods: {
    // 获取列表数据
    // 页数发生变化调用
    async getList(pager = 1) {
      this.page = pager;
      // 解构vm的数据
      const { page, limit } = this;
      //  重构请求参数
      let data = { pageNum: page, pageSize: limit };
      let result = await this.$API.column.reqGetColumn(data);
      if (result.status == 200) {
        this.total = result.data.total;
        this.list = result.data.records;
      }
    },
    // 打开弹窗时的回调
    async open() {
      let result = await this.$API.column.reqGetAll();
      if (result.status == 200) {
        result.data.forEach((item) => {
          if (item.id != 3) {
            this.columnList.push(item);
          }
        });
      }
    },
    // 新增子栏目按钮
    addColumn() {
      this.dialogVisible = true;
      this.columnList = [];
      this.title = "新增子栏目";
      // 打开弹窗清空表单数据
      this.formList = {
        columnName: "",
        image: "",
        moduleId: "",
      };
      this.imageUrl = "";
    },
    // 编辑按钮
    editColumn(row) {
      // 点击编辑浅拷贝数据，赋值给弹窗表单
      this.columnList = [];
      this.formList = { ...row };
      this.dialogVisible = true;
      this.title = "修改子栏目";
    },
    // 关闭弹窗的回调
    handleClose(done) {
      this.$confirm("您还未确认保存，确认退出吗？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 文件上传成功时的钩子
    handleAvatarSuccess(res, file) {
      this.formList.image = res.data.domain + res.data.path + "?download=0";
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 每页展示数量发生改变时触发
    handleSizeChange(limit) {
      this.limit = limit;
      this.getList();
    },
    // 确认按钮
    addOrEdit() {
      this.$refs.ruleFrom.validate(async (success) => {
        if (success) {
          let columnDto = {};
          // 判断是否携带id，根据有无id配置请求参数
          if (this.formList.id) {
            columnDto.id = this.formList.id;
            columnDto.columnName = this.formList.columnName;
            columnDto.moduleId = this.formList.moduleId;
            columnDto.image = this.formList.image || "";
          } else {
            columnDto = this.formList;
          }
          let result = await this.$API.column.reqAddOredit(columnDto);
          if (result.status == 200) {
            this.$message({
              message: this.formList.id ? "修改成功" : "新增成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.getList(this.formList.id ? this.page : 1);
          }
        } else {
          return false;
        }
      });
    },
    // 设为 || 取消导航图
    async setImg(row) {
      let result = await this.$API.column.reqSetimg({ id: row.id });
      if (result.status == 200) {
        this.getList(this.page);
        this.$message({
          message: "设置成功",
          type: "success",
        });
      }
    },
    // 确认删除按钮
    async deleteColumn(row) {
      let result = await this.$API.column.reqDelete(row.id);
      if (result.status == 200) {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        // 当当前页删完，自动跳到上一页
        this.getList(this.list.length > 1 ? this.page : this.page - 1);
      }
    },
  },
  // 计算属性
  computed: {
    // 计算token，配置请求头部
    headers() {
      return {
        Authorization: "Bearer " + getToken(),
      };
    },
  },
};
</script>

<style>
.box {
  height: 100%;
  overflow-y: auto;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
